package com.studentManagement.filter;

import com.studentManagement.dao.TeacherDao;
import com.studentManagement.daoImpl.TeacherDaoImpl;
import com.studentManagement.po.Teacher;
import com.studentManagement.utils.CookieUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Administrator on 2017/4/26 0026.
 */
@WebFilter(filterName = "LoginFilter")
public class LoginFilter implements Filter {
    String noFilter = null;

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//        chain.doFilter(req,resp);
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //cookie
        CookieUtil cookieUtil = new CookieUtil();
        Cookie cookies[] = request.getCookies();
        String cookieUsername = cookieUtil.getCookieValueByName(cookies, "autoUsername");
        String cookiePassword = cookieUtil.getCookieValueByName(cookies, "autoPassword");
        TeacherDao teacherDao = new TeacherDaoImpl();
        try {
            Teacher teacher = teacherDao.queryTeacherByTId(cookieUsername);
            if (teacher!=null&&teacher.getTeacher_key() != null&&(teacher.getTeacher_key()).equals(cookiePassword)  ) {
                request.getSession().setAttribute("teacher", teacher);
                chain.doFilter(req, resp);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //某些页面不跳转到login
        String[] arr = noFilter.split(";");
        for (int i = 0; i < arr.length; i++) {
            if (request.getRequestURL().indexOf(arr[i]) != -1) {
                chain.doFilter(req, resp);
                return;
            }
        }
        if (request.getSession().getAttribute("teacher") != null||request.getSession().getAttribute("student") != null) {
            chain.doFilter(req, resp);
            return;
        } else {
            response.sendRedirect(request.getContextPath() + "/jsp/teacher/login.jsp");
        }
    }

    public void init(FilterConfig config) throws ServletException {
        noFilter = config.getInitParameter("NoFilter");
    }
}
